<?php
/**
 * Created by PhpStorm.
 * User: zhenl
 * Date: 2022/12/18
 * Time: 22:57
 */

namespace App\Http\Controllers;


use App\Constant;
use App\Models\Attribute;
use App\Models\AttributeValue;
use App\Models\Brand;
use App\Models\Product;
use App\Models\ProductStock;
use App\Models\Seller;
use App\Models\TaskModel;
use App\Models\Upload;
use App\Models\VisitHistoryModel;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class TaskController
{
    public function init()
    {
        $sellers = Seller::all();
        foreach ($sellers as $k => $s) {
            // 每日初始化
            date_default_timezone_set("Asia/Shanghai");
            $date = date('Y-m-d');
            VisitHistoryModel::updateOrCreate([
                'seller_id' => $s->id,
                'current_date' => $date
            ], [
                'user_id' => $s->user_id,
                'today_visit' => 0,
                'order_visit' => 0,
                'refresh_visit' => 0,
                'total_visit' => 0,
            ]);
            date_default_timezone_set(config('app.timezone', 'UTC'));
            // 统计昨日
            if ($s->yesterday_visit_history) {
                $s->yesterday_visit_history->fill([
                    'total_visit' => $s->yesterday_visit_history->today_visit + $s->yesterday_visit_history->order_visit + $s->yesterday_visit_history->refresh_visit
                ])->save();
            }

            // 统计最近7天
            $start_7 = date('Y-m-d H:i:s', strtotime('7 days ago midnight'));
            $end_7 = date('Y-m-d H:i:s', strtotime('today midnight') - 1);
            $s->fill([
                'last_7_visitors' => $s->visit_history()->whereBetween('created_at', [$start_7, $end_7])->sum('total_visit') ?? 0,
            ])->save();

            // 统计最近30天
            $start_30 = date('Y-m-d H:i:s', strtotime('30 days ago midnight'));
            $end_30 = date('Y-m-d H:i:s', strtotime('today midnight') - 1);
            $s->fill([
                'last_30_visitors' => $s->visit_history()->whereBetween('created_at', [$start_30, $end_30])->sum('total_visit') ?? 0,
            ])->save();
        }
    }


    public function visit()
    {
        $sellers = Seller::all();
        foreach ($sellers as $k => $s) {
            $model = $s->today_visit_history;
            if (!$model) {
                continue;
            }
            $model->fill([
                'today_visit' => ceil($model->today_visit + $s->today_visitors / 24)
            ])->save();
        }
    }


    /**
     * 按关键字列表搜索商品
     *
     * @param Request $request
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function search_product(Request $request)
    {
        set_time_limit(300);
        ini_set('memory_limit', '512M');

        //.商品分类
        $category_id = 1;

        $keywords = [
            "Samsung",
        ];

        $client = new Client([
            // Base URI is used with relative requests
            'base_uri' => "https://api09.99api.com/",
            // You can set any number of default request options.
            'timeout' => 30,
        ]);
        foreach ($keywords as $search) {
            $exist_product_list = TaskModel::where('type', Constant::TASK_TYPE_SCRAPE_PRODUCT)->pluck('is_finish', 'hash')->toArray();
            $page = 1;
            $response = $client->get('/shopee/search', [
                'query' => [
                    'apikey' => '07B813F6C811BB8E81F75655FBB3AC75',
                    'keyword' => $search,
                    'page' => $page,
                    'market' => 'my',
                    'order' => 'pop',
                ],
            ]);
            $result = json_decode((string)$response->getBody(), true);
            Log::error("99product info:" . json_encode($result));
//            dd($result);
            if ($result['retcode'] == '0000') {
                foreach ($result['data']['items'] as $item) {
                    if (!in_array(md5($item['shopId'] . $item['itemId']), $exist_product_list)) {
                        TaskModel::create([
                            'type' => Constant::TASK_TYPE_SCRAPE_PRODUCT,
                            'hash' => md5($item['shopId'] . $item['itemId']),
                            'data' => array_merge($item, compact('category_id')),
                            'is_finish' => Constant::NO,
                        ]);
                    }
                }
            } else {
                \Log::error("99 error:" . json_encode($result, JSON_UNESCAPED_UNICODE));
            }
        }


    }

    /**
     * 同步商品
     *
     * @param Request $request
     */
    public function scrape_product(Request $request)
    {
        set_time_limit(60);
        ini_set('memory_limit', '512M');

        $client = new Client([
            // Base URI is used with relative requests
            'base_uri' => "https://api09.99api.com/",
            // You can set any number of default request options.
            'timeout' => 30,
        ]);
        $task_list = TaskModel::where('type', Constant::TASK_TYPE_SCRAPE_PRODUCT)->where('is_finish', Constant::NO)->get();
        foreach ($task_list as $task) {
            $item_id = $task['data']['itemId'];
            $shop_id = $task['data']['shopId'];
            $response = $client->get('/shopee/goodsDetail', [
                'query' => [
                    'apikey' => '07B813F6C811BB8E81F75655FBB3AC75',
                    'itemId' => $item_id,
                    'shopId' => $shop_id,
                    'market' => 'my',
                ],
            ]);
            $result = json_decode((string)$response->getBody(), true);
            Log::error("99detail info:" . json_encode($result));
            $remote_data = [];
            $task->fill(['response' => $result])->save();
            if ($result['retcode'] != '0000') {
                \Log::error("99 error:" . json_encode($result, JSON_UNESCAPED_UNICODE));
                continue;
            }

            $remote_data = $result['data'];
            $filter_sku = array_filter($remote_data['skus'], function ($v) {
                return !empty($v['name']) && ($v['price'] > 0);
            });
            if (count($filter_sku) == 0) {
                \Log::error("99 sku empty:" . json_encode($remote_data['name'], JSON_UNESCAPED_UNICODE));
                continue;
            }

            // 第一遍处理基础数据
            $description = '';
            $product_name = '';
            $brand_name = '';
            $min_price = $max_price = 0;
            // 1.确定每个商品拥有的规格组(仅双规格可以加入)
            if (empty($remote_data['tierVariations'][0]['name']) || empty($remote_data['tierVariations'][1]['name'])) {
                \Log::error("99 sku group empty:" . json_encode($remote_data['tierVariations'], JSON_UNESCAPED_UNICODE));
                continue;
            }
            $attribute1_model = Attribute::updateOrCreate([
                'name' => $remote_data['tierVariations'][0]['name'],
            ], []);
            $attribute2_model = Attribute::updateOrCreate([
                'name' => $remote_data['tierVariations'][1]['name'],
            ], []);
            $attr_arr = $temp_choice = [];
            $choice1_arr = ['attribute_id' => $attribute1_model->id, 'values' => []];
            $choice2_arr = ['attribute_id' => $attribute2_model->id, 'values' => []];
            // 处理属性产品类1和产品类2
            foreach ($remote_data['tierVariations'][0]['options'] as $vvv1) {
                if (trim($vvv1)) {
                    $attribute_value_color_model = AttributeValue::updateOrCreate([
                        'attribute_id' => $attribute1_model->id, 'value' => $vvv1
                    ]);
                    $attr_arr[] = $attribute1_model->id;
                    $attr_arr = array_unique($attr_arr);
                    $choice1_arr['values'][] = $vvv1;
                    $choice1_arr['values'] = array_unique($choice1_arr['values']);
                }
            }

            foreach ($remote_data['tierVariations'][1]['options'] as $vvv2) {
                if (trim($vvv2)) {
                    $attribute_value_size_model = AttributeValue::updateOrCreate([
                        'attribute_id' => $attribute2_model->id, 'value' => $vvv2
                    ]);
                    $attr_arr[] = $attribute2_model->id;
                    $attr_arr = array_unique($attr_arr);
                    $choice2_arr['values'][] = $vvv2;
                    $choice2_arr['values'] = array_unique($choice2_arr['values']);
                }
            }


            if (in_array($attribute1_model->id, $attr_arr)) {
                $temp_choice[] = $choice1_arr;
            }
            if (in_array($attribute2_model->id, $attr_arr)) {
                $temp_choice[] = $choice2_arr;
            }

            // 2.处理图片新增
            $image_ids = [];
            foreach ($remote_data['images'] as $image_url) {
                $image_model = Upload::updateOrCreate([
                    'file_original_name' => $image_url
                ], [
                    'file_name' => $image_url,
                    'user_id' => 0,
                    'file_size' => 8888,
                    'extension' => 'jpg',
                    'type' => 'image'
                ]);
                $image_ids[] = $image_model->id;
            }
            $description = $remote_data['description'];
            $product_name = $remote_data['name'];
            $brand_name = $remote_data['brand'];
            //$min_price = $remote_data['priceMin'];
            //$max_price = $remote_data['priceMax'];
            $pro_price = $remote_data['price'] / 10000;

            if (!$product_name || count($image_ids) == 0) {
                continue;
            }
            // 3.处理所属品牌
            if ($brand_name) {
                $brand_model = Brand::updateOrCreate([
                    'name' => $brand_name,
                ], [
                    'logo' => 0,
                    'top' => 0,
                    'slug' => preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', strtolower($brand_name))),
                    'meta_title' => $brand_name,
                    'meta_description' => $brand_name,
                ]);
            }

            // 主档案商品
            $product_model = Product::create([
                'name' => $product_name,
                'user_id' => 1,
                'category_id' => $task['data']['category_id'] ?: 0,
                'brand_id' => $brand_model ? $brand_model->id : 0,
                'photos' => implode($image_ids, ','),
                'thumbnail_img' => $image_ids ? $image_ids[0] : '',
                'description' => $description,
                'unit_price' => $pro_price / 4.49,
                'purchase_price' => 0,
                'variant_product' => count($remote_data['skus']) > 1 ? 1 : 0,
                'attributes' => json_encode($attr_arr),
                'choice_options' => json_encode($temp_choice),
                'colors' => json_encode([]),
                'published' => 1,
                'approved' => 1,
                'current_stock' => count($remote_data['skus']) * 1000,
                'min_qty' => 1,
                'low_stock_quantity' => 1,
                'discount' => 0,
                'discount_type' => 'amount',
                'shipping_type' => 'free',
                'shipping_cost' => 0,
                'meta_title' => $product_name,
                'slug' => preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', strtolower($product_name))),
                'refundable' => 0,
                'cpk' => 1
            ]);

            // 第二轮处理子规格插入
            $sku_num = 0;
            foreach ($remote_data['skus'] as $temp_sku) {
                if ($sku_num >= 5) {
                    break;
                }
                $sku_arr = [];
                $child_spec1 = $remote_data['tierVariations'][0]['options'][$temp_sku['tier_index'][0]];
                if (trim($child_spec1)) {
                    $sku_arr[] = str_replace(' ', '', $child_spec1);
                }
                $child_spec2 = $remote_data['tierVariations'][1]['options'][$temp_sku['tier_index'][1]];
                if (trim($child_spec2)) {
                    $sku_arr[] = str_replace(' ', '', $child_spec2);
                }

                $sku_price = $temp_sku['price'] / 10000;
                Log::error("sku的价格是:" . $sku_price);
                ProductStock::create([
                    'product_id' => $product_model->id,
                    'variant' => implode('-', $sku_arr),
                    'sku' => implode('-', $sku_arr),
                    'price' => $sku_price / 4.49,
                    'qty' => 1000
                ]);
                $sku_num++;
            }

            $task->fill(['is_finish' => Constant::YES])->save();
            sleep(1);
        }
    }
}